package com.gec.web;

import com.gec.domain.Document;
import com.gec.domain.Employee;
import com.gec.domain.User;
import com.gec.service.DocumentService;
import com.gec.service.impl.DocumentServiceImpl;
import com.gec.utils.CrossRegion;
import com.gec.utils.PageModel;
import com.google.gson.Gson;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import javax.xml.crypto.Data;
import java.io.*;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@WebServlet(urlPatterns = {"/findAlldocument","/findDocumentById","/addDocument","/downloadDocument","/deleteDocument"})

@MultipartConfig
public class DocumentController extends HttpServlet {
    //获取service
    DocumentService service=new DocumentServiceImpl();
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //设置请求编码
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        //跨域设置
        CrossRegion.setCross(response);

        if("OPTIONS".equals(request.getMethod())){
            response.setStatus(HttpServletResponse.SC_OK);
            return;
        }
        //请求的servlet路径
        String servletPath = request.getServletPath();

        if(servletPath.equals("/findAlldocument")){
            findalldocument(request,response);
        }else if(servletPath.equals("/findDocumentById")){
            finddocumentbyid(request,response);
        }else if(servletPath.equals("/addDocument")){
            adddocument(request,response);
        }else if(servletPath.equals("/downloadDocument")){
            downloadDocument(request,response);
        }else if(servletPath.equals("/deleteDocument")){
            deletedocument(request,response);
        }
    }

    /**删除文件*/
    private void deletedocument(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String id = request.getParameter("id");
        service.deleteDocument(Integer.parseInt(id));
        Map<String,Object>map=new HashMap<>();
        map.put("code",200);
        map.put("message","success");

        Gson gson=new Gson();
        String json = gson.toJson(map);

        response.getWriter().write(json);
    }

    /**下载文件*/
    private void downloadDocument(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String id = request.getParameter("id");

        //设置响应头
        response.setHeader("content-disposition","attachment;filename=" + id);
        //连接到数据库
        Document document = service.downDocument(id);
        //设置后缀名
        String end=null;
        //判断后缀名
        if (document.getFiletype().equals("image/jpeg")){
            end=".jpg";
        }else if(document.getFiletype().equals("/text/plain")){
            end=".text";
        }
        System.out.println(document);
        //拼接，下载到指定位置
        File file=new File("D:\\ACER\\Documents"+File.separator+id+end);
        //如果没有，就创建一个文件
        if (!file.exists()){
            try {
                file.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        try(InputStream is=new FileInputStream(file);
            OutputStream os=response.getOutputStream();
        ){
            int len=0;
            byte[]b=new byte[1024];
            //循环读取
            while((len=is.read(b))>0){
                os.write(b,0,len);
            }
        }catch (IOException e){
            e.printStackTrace();
        }
        //使用数组组合
        Map<String,Object> map=new HashMap<>();
        map.put("file",file);
        //使用Gson返回
        Gson gson=new Gson();
        String json = gson.toJson(map);
        //响应到前台
        response.getWriter().write(json);
    }

    /**上传文件*/
    private void adddocument(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        //获得上传组件
        Part file = request.getPart("file");

        System.out.println(file);
        //文件大小
        System.out.println("文件大小："+file.getSize());
        //文件信息
        System.out.println("文件类型："+file.getContentType());
        //获得页面传来的文档标题
        String title = request.getParameter("title");
        //获得文档描述
        String remark = request.getParameter("remark");
        //文档类型
        String filetype = file.getContentType();
        //文档名称
        //String filename = file.getName();
        //System.out.println("filename:"+filename);

        //设置响应头
        String cd = file.getHeader("Content-Disposition");
        //截取不同类型的文件需要自行判断
        String filename = cd.substring(cd.lastIndexOf("=")+2, cd.length()-1);
        System.out.println("文件名:" + filename);

        Document document=new Document();
        //用io流来接收
        InputStream inputStream = file.getInputStream();
        //页面传来的文件大小是byte类型，用byte接收，
        byte[] b=new byte[(int)file.getSize()];
        //接收完的数据存入io流中
        int read = inputStream.read(b);
        //一定要记得关闭io流
        inputStream.close();
        System.out.println("read = " + read);
        //将接收的数据传到document里面
        document.setFileBytes(b);
        document.setTitle(title);

        document.setFileName(filename);
        document.setFiletype(filetype);
        document.setRemark(remark);
        document.setCreateDate(new Date());

        User user = new User();
        //先固定用户为1
        user.setId(1);
        document.setUser(user);
        //传到数据库添加
        service.addDocument(document);

        Map<String ,Object>map=new HashMap<>();
        map.put("code",200);
        map.put("message","success");
        Gson gson=new Gson();
        String json = gson.toJson(map);
        response.getWriter().write(json);
    }

    /**获取单个文件信息*/
    private void finddocumentbyid(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String id = request.getParameter("id");
        service.findById(Integer.parseInt(id));

        Map<String,Object>map=new HashMap<>();
        map.put("code",200);
        map.put("message","success");

        Gson gson=new Gson();
        String json = gson.toJson(map);

        response.getWriter().write(json);
    }

    /**获取全部文件信息*/
    private void findalldocument(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String pageIndex=request.getParameter("pageIndex");
        int page=!"".equals(pageIndex) && pageIndex !=null ? Integer.parseInt(pageIndex) : 1;
        PageModel model=new PageModel();
        model.setPageIndex(page);

        List<Document> documents=null;


        //获取页面传来的文件名
        String fileName = request.getParameter("fileName");
        Document document=new Document();

        document.setFileName(fileName);


        //获取分页
        int count=service.getTotalDocumentCount(document);
        model.setTotalRecoreSum(count);
        documents = service.findAlldocument(document, model);

        //使用数组组合
        Map<String,Object> map=new HashMap<>();
        map.put("model",model);
        map.put("documents",documents);
        //使用Gson返回
        Gson gson=new Gson();
        String json = gson.toJson(map);
        //响应到前台
        response.getWriter().write(json);
    }
}
